package com.atguigu.tingshu.account.service.impl;

import com.atguigu.tingshu.account.mapper.UserAccountDetailMapper;
import com.atguigu.tingshu.account.mapper.UserAccountMapper;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.model.account.UserAccount;
import com.atguigu.tingshu.model.account.UserAccountDetail;
import com.atguigu.tingshu.vo.account.AccountLockVo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements UserAccountService {

	@Autowired
	private UserAccountMapper userAccountMapper;

	@Autowired
	private UserAccountDetailMapper detailMapper;

	@Autowired
	private RedisTemplate redisTemplate;

	@Autowired
	private RabbitTemplate rabbitTemplate;

	@Transactional
	@Override
	public void saveAccount(Long userId) {
		UserAccount userAccount = new UserAccount();
		userAccount.setUserId(userId);
		this.save(userAccount);
	}

	@Transactional(rollbackFor = Exception.class)
    @Override
    public boolean checkAndDeduction(AccountLockVo accountLockVo) {
		//更新记录的行数 大于0表示成功  返回true
		boolean flag = userAccountMapper.checkAndDeduction(accountLockVo);
		if(!flag){//账户余额扣除失败!
			throw new GuiguException(ResultCodeEnum.ACCOUNT_LESS);
		}
		//保存流水
		UserAccountDetail userAccountDetail = new UserAccountDetail();
		userAccountDetail.setTradeType(SystemConstant.ACCOUNT_TRADE_TYPE_MINUS);//消费类型：购物
		userAccountDetail.setUserId(accountLockVo.getUserId());
		userAccountDetail.setOrderNo(accountLockVo.getOrderNo());
		userAccountDetail.setTitle(accountLockVo.getContent());
		userAccountDetail.setAmount(accountLockVo.getAmount());
		detailMapper.insert(userAccountDetail);
		return true;
    }

}
